'use strict'

const Controller =  require('egg').Controller;
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
class UserController  extends Controller {
    async login(){
        let { account,password } = this.ctx.request.body;
        let res = await this.ctx.model.User.findOne({
            where:{
                account:account
            }
        });
        let boolean = bcrypt.compareSync(password,res.password);
        if(!boolean){
            this.ctx.body = {
                code:-1,
            };
            return;
        };
        console.log('res',res);
        let token = jwt.sign({
            uid:res.uid,
        },this.config.secret);
        let server = this.config.cServer[0];
        this.ctx.body = {
            token:token,
            server:server
        };
    };
    async register(){
        let { account,password } = this.ctx.request.body;
        let res = await this.ctx.model.User.findOne({
            where:{
                account:account
            }
        });
        if(res){
            this.ctx.body = {
                code:-1,
            };
            return;
        };
        let salt = bcrypt.genSaltSync(10);
        const hash = bcrypt.hashSync(password, salt);
        let last_login_time = new Date().toJSON().slice(0, 19).replace('T', ' ');
        const ip = this.ctx.request.ip;
        let uid = await this.ctx.model.User.max('uid');
        if(!uid) uid = 1000000;
        uid = uid + 1;
        let status = 1;
        let user = await this.ctx.model.User.create({
            last_login_time:last_login_time,
            account:account,
            password:hash,
            last_login_ip:String(ip),
            uid:uid,
            status:status
        });
        let role = {
            userid:uid,
            coin:0,
            diamond:0,
            gems:0,
            gameid:10000,
            img:'',
            sex:1,
            name:account,
            status:1
        };
        await this.ctx.model.Role.create(role);
        if(user){
            this.ctx.body = {
                code:200
            };
        }else
        {
            this.ctx.body = {
                code:-1,
            };
        }
    }
}
module.exports = UserController;